package controllers

import (
	"book/models"
	beego "github.com/beego/beego/v2/server/web"
)

type BookController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *BookController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Book{}).Count(&count)
	offset := (page - 1) * size
	var book models.Book
	err := models.DB.Offset(offset).Limit(size).Find(&book).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "展示成功",
			Data: book,
		}
		c.ServeJSON()
	}
}

func (c *BookController) Add() {
	name := c.GetString("name")
	author := c.GetString("author")
	status := c.GetString("status")
	book := models.Book{
		Name:   name,
		Author: author,
		Status: status,
	}
	err := models.DB.Create(&book).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: book,
		}
		c.ServeJSON()
	}
}
